﻿using System;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;
using System.Xml;
using System.Xml.Linq;

namespace WpfWhenNoAeraTheme
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            GetVisualTreeInfo(listView1);
            string temp = GetTemplateXamlCode(listView1);
            Debug.WriteLine("Template::");
            Debug.WriteLine(temp);

            var svALlItems = (ScrollViewer)(VisualTreeHelper.GetChild(listView1, 0) as Decorator).Child;
        }

        string GetVisualTreeInfo(DependencyObject target)
        {
            int i = 0;
            int childCount = 0;
            DependencyObject parentObject = target;
            DependencyObject childObject = null;
            string format = "{0}Rank:{1}    childIndex:{2}   {3}   ";
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("VisualTree:");
            while (true)
            {
                childCount = VisualTreeHelper.GetChildrenCount(parentObject);
                if (childCount == 0) break;

                for (int j = 0; j < childCount; j++)
                {
                    childObject = VisualTreeHelper.GetChild(parentObject, j);
                    stringBuilder.AppendLine(string.Format(format, new string(' ', i), i, j, childObject));
                }

                if (childObject == null) break;
                parentObject = childObject;
                i++;
            }
            Debug.WriteLine(stringBuilder.ToString());
            return stringBuilder.ToString();

        }

        string GetTemplateXamlCode(Control ctrl)
        {
            FrameworkTemplate template = ctrl.Template;
            return XElement.Parse(XamlWriter.Save(template)).ToString();           
        }

















    }
}
